package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private Button btn_bind_service,btn_unbind_service,btn_play_music,btn_stop_music,btn_calc;
    private ServiceConnection connection;
    private MyService.MyBinder myBinder;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn_bind_service=findViewById(R.id.btn_bind_service);
        btn_unbind_service=findViewById(R.id.btn_unbind_service);
        btn_play_music=findViewById(R.id.btn_play_music);
        btn_stop_music=findViewById(R.id.btn_stop_music);
        btn_calc=findViewById(R.id.btn_calc);
        connection=new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
                Log.e("ServiceConnection","onServiceConnected");
                myBinder=(MyService.MyBinder)iBinder;
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                Log.e("ServiceConnection","onServiceConnected");

            }
        };
        btn_calc.setOnClickListener((e)->{
            int result=myBinder.cal1n(100);
            Toast.makeText(MainActivity.this, "结果是"+result, Toast.LENGTH_SHORT).show();
        });

        btn_play_music.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                myBinder.play();
            }
        });
        btn_stop_music.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                myBinder.stop();
            }
        });



        btn_bind_service.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent();
                intent.setClass(MainActivity.this,MyService.class);
                bindService(intent,connection,BIND_AUTO_CREATE);
            }
        });
        btn_unbind_service.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                unbindService(connection);
            }
        });
    }
}